//
//  YbrPlayer.m
//  wifibox
//
//  Created by os X 10.9 on 14-12-18.
//  Copyright (c) 2014年 yinbaner. All rights reserved.
//

// 播放状态和播放列表改变的时候发通知, 进度条播放的时间的使用 delegate

#import "YbrPlayer.h"
#import "YbrMusicItem.h"
#import "AudioStreamer.h"
#import <MediaPlayer/MediaPlayer.h>
#import "YbrFileUtils.h"
#import "YbrSandBox.h"
#import "YbrMusicPlayUtil.h"
#import "NSString+Ybr.h"
#import "YbrSystemUtil.h"

@interface YbrPlayer () <AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *avaPlayer;     // 播放本地用的
@property (nonatomic, strong) AudioStreamer *httpPlayer;    // 播放网络上用的
@property (nonatomic, strong) NSArray *musiclist;           // 播放的musiclist
@property (nonatomic) int playPos;                          // 正在播放的是哪一个
@property (nonatomic) int playLen;                          // 播放的list的长度
@property (nonatomic ,strong) YbrMusicItem *musicItem;      // 音乐的Item
@property (nonatomic) BOOL isSupposeToBePlaying;            // 是否正在播放
@property (nonatomic) int playType;                         // 播放的类型  0 表示本地的  1表示网络的 2表示dlna

@property (nonatomic) int errNum;                           // 播放音乐的时候错误的个数
@property (nonatomic) BOOL isWillPlay;                      // 是否要马上播放


@end


@implementation YbrPlayer


static YbrPlayer * ybrPlayer;

// 如果想实现单例模式,重写此方法
// 该方法线程安全
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t oncePredicate;   // 此对象存在多线程中,
    
    // 这里的静态代码快只执行一次
    dispatch_once(&oncePredicate, ^{
        ybrPlayer               =   [super allocWithZone:zone];
        ybrPlayer.playPos       =   -1;
        ybrPlayer.playLen       =   -1;
        ybrPlayer.playType      =   -1;
        ybrPlayer.isWillPlay    =   YES;
    });
    return ybrPlayer;
}


+(YbrPlayer *) getInstance {
    return [[self alloc] init];
}


//-(id)init {
//    self = [super init];
//    self.playPos = -1;
//    self.playLen = -1;
//    self.playType = -1;
//    self.isWillPlay = YES;
// 
//    return self;
//}

-(void) addMusiclist:(NSArray *) musiclist position:(int) position {
    self.isWillPlay = NO;
    self.musiclist = musiclist;
    self.playLen = (int)musiclist.count;
    self.playPos = position;
    
    [self playCurrent];
}

// Arr : YbrMusicItem对象(默认先播放第一个)
-(void) playAll:(NSArray *) musiclist {
    [self playAll:musiclist position:0];
}


-(void) playAll:(NSArray *) musiclist position:(int) position {  // 添加了一个播放哪一个
    
    self.isWillPlay = YES;
    
    self.musiclist = musiclist;
    self.playLen = (int)musiclist.count;
    self.playPos = position;
    [[NSNotificationCenter defaultCenter]postNotificationName:PlayerStateChange object:nil];
    [self playCurrent];
}

// 播放正在播放的
-(void) playCurrent {
    if(self.musiclist == nil || self.playLen == 0 || self.musiclist.count <= self.playPos) {
        return;
    }
    
    self.musicItem = [self.musiclist objectAtIndex:self.playPos];

    if((![self.musicItem.file hasPrefix:@"ipod-library"] && ![self.musicItem.file hasPrefix:@"/var/mobile/Applications"]) && ![NSString isEmpty:self.musicItem.file] && ![YbrFileUtils isFileExist:self.musicItem.file]) {
        
        if(![YbrFileUtils isFileExist:[NSHomeDirectory() stringByAppendingString:self.musicItem.file]]){
            self.musicItem.file = [YbrSandBox audioAppendFilePath:self.musicItem.file];
        }
    }
    
    
    if([NSString isEmpty:self.musicItem.file] || (![self.musicItem.file hasPrefix:@"ipod-library"] && ![YbrFileUtils isFileExist:self.musicItem.file])) {
        // 使用在线的
        while (![self playHttpPath:self.musicItem.downloadurl]) {
            if(![self playErrAction]) {
                break;
            }
        }
    }else {
        // 播放本地的音乐
        while (![self playFilePath:self.musicItem.file]) {
            if(![self playErrAction]) {
                break;
            }
        }
    }
   
    [self setMetaChange];
    [self showInfoInLockedScreen];
    
}

// 播放失败的时候要干的事情
-(BOOL) playErrAction {
    // 如果列表当中所有的歌曲全部播放不了
    if(self.errNum ++ < self.playLen) {
        int pos = [self getNextPos];
        self.playPos = pos;
        return YES;
    }else {
        self.errNum = 0;
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此列表的歌曲全部失效,请选择其他列表" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return NO;
    }
}

// 在锁屏界面显示歌曲信息
- (void)showInfoInLockedScreen
{
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    
    info[MPMediaItemPropertyTitle] = self.musicItem.musicName == nil ? @"未知歌曲" : self.musicItem.musicName;
    info[MPMediaItemPropertyArtist] = self.musicItem.singername == nil ? @"未知歌手" : self.musicItem.singername;
    info[MPMediaItemPropertyAlbumTitle] = self.musicItem.albumname == nil ? @"未知专辑" : self.musicItem.albumname;
    info[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithInt:self.musicItem.duration];
    
    // 图片
   
    if([NSString isEmpty:self.musicItem.img]){
        UIImage *img = [UIImage imageNamed:@"defaultAlbumSmall"];
        info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:img];
    }else{
        NSString *imgurl = [YbrMusicPlayUtil getBitmap];
        
        if(![imgurl hasPrefix:@"http"] && ![imgurl hasSuffix:@"png"]) {
            imgurl = [NSString stringWithFormat:@"%@%@" ,ImgLoad ,imgurl];
        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            UIImage *img;
            if ([imgurl hasPrefix:@"http"]) {
                img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgurl]]];
            }else{
                img = [YbrSandBox readImage:imgurl];
            }
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                if (img) {
                    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:img];
                    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
                }
                
            });
        });

    }
    
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
    
}

#pragma mark dlna播放
// 为了可以在后台可以运行
-(void) playDlna {
    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(dispatchQueue, ^(void) {
        NSBundle *mainBundle = [NSBundle mainBundle];
        NSString *filePath = [mainBundle pathForResource:@"silence" ofType:@"mp3"];
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];

        NSError *error = nil;
        
        self.playType = 0;
        // 先将之前的关闭掉
        if(self.avaPlayer) {
            [self.avaPlayer stop];
        }
        
        @try {
            if(self.httpPlayer) {
                [self.httpPlayer stop];
                self.httpPlayer = nil;
            }
        }
        @catch (NSException *exception) {
            NSLog(@"出错了  %@" ,exception);
        }

        self.avaPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
        [self.avaPlayer setNumberOfLoops:-1];
        if ([self.avaPlayer prepareToPlay] && [self.avaPlayer play]){
            NSLog(@"Successfully started playing...");
        } else {
            NSLog(@"Failed to play.");
        }
    });
}


-(BOOL) playHttpPath:(NSString *) musicPath {
    @synchronized(self) {
        
        self.playType = 1;
        NSLog(@"播放网络的路径的时候 ===   %@" ,self.httpPlayer);
        
        if(self.httpPlayer) {
            [[NSNotificationCenter defaultCenter]removeObserver:self name:ASStatusChangedNotification object:self.httpPlayer];
            [self.httpPlayer stop];
            self.httpPlayer = nil;
        }
        
        if(self.avaPlayer) {
            [self.avaPlayer stop];
            self.avaPlayer = nil;
        }
        
//        if(![musicPath hasPrefix:@"http"]) {
//            musicPath = [NSString stringWithFormat:@"%@%@" ,MP3Url ,musicPath];
//        }
        
        // 将URL进行编码
//        NSString *escapedValue = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef) musicPath, NULL, NULL, kCFStringEncodingUTF8));
        NSURL *url = [NSURL URLWithString:@"escapedValue"];
        
        NSLog(@"网络歌曲的播放路径是  %@" ,url);
        @try {
//            self.httpPlayer = [[AudioStreamer alloc] initWithURL:url];
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playbackStateChanged:) name:ASStatusChangedNotification object:self.httpPlayer];
            
            if(self.isWillPlay) {
                if([YbrSystemUtil GetCurrntNet] == NotReachable) {
                    return NO;
                }
                [self.httpPlayer start];
            }
            [self setPlayStateChange];
        }
        @catch (NSException *exception) {
            NSLog(@"在线播放器出错   %@" ,exception);
            return NO;
        }
        return YES;
    }
}

// 播放本地的歌曲
-(BOOL) playFilePath:(NSString *) filePath {
    self.playType = 0;
    // 先将之前的关闭掉
    if(self.avaPlayer) {
        [self.avaPlayer stop];
        self.avaPlayer = nil;
    }
    @try {
        if(self.httpPlayer) {
            [self.httpPlayer stop];
            self.httpPlayer = nil;
        }
    }
    @catch (NSException *exception) {
        NSLog(@"出错了  %@" ,exception);
    }
    
    NSURL *url = [NSURL URLWithString:filePath];
    if(url == nil) {
        url = [NSURL fileURLWithPath:filePath isDirectory:NO];
    }
    
    self.avaPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.avaPlayer.delegate = self;
//    self.avaPlayer.currentTime = [YbrTimerUtil makeTimeInt:self.musicItem.lastPlayTime];
    [self.avaPlayer setNumberOfLoops:0];
    BOOL isOK = NO;
    isOK = [self.avaPlayer prepareToPlay];
    if(!isOK) {
        return NO;
    }
    if(self.isWillPlay) {
        isOK = [self.avaPlayer play];
        if (self.lastTime != 0) {
            [self seek:self.lastTime];
            self.lastTime = 0;
        }
    }
    [self setPlayStateChange];

    return isOK;
}

- (void)playbackStateChanged:(NSNotification *)aNotification
{
	if ([self.httpPlayer isWaiting]) {
        NSLog(@"isWaiting");
	}
	else if ([self.httpPlayer isPlaying]) {
        if (self.lastTime != 0) {
            [self seek:self.lastTime];
            self.lastTime = 0;
        }
        [self setPlayStateChange];
        NSLog(@"正在播放");
	}
	else if ([self.httpPlayer isIdle] /** && isPlayOrPause*/) {
        NSLog(@"该下一曲了");
        [self Next];
	}
    else {
        [self setPlayStateChange];
        NSLog(@"暂停");
    }
}

// 播放状态发生改变了 (暂停,播放,停止)
-(void) setPlayStateChange {
    [self playStateChange];
}

-(void)playStateChange
{
    [[NSNotificationCenter defaultCenter] postNotificationName:PlayerStateChange object:self.musicItem];
}

// 播放的项目发生改变 (上下曲 ,播放列表的改变)
-(void) setMetaChange {
    // 保存正在播放的是哪一个
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:self.playPos] forKey:@"musicPos"];
    [self metaStateChange];
}

-(void)metaStateChange
{
     [[NSNotificationCenter defaultCenter] postNotificationName:MetaStateChange object:self.musicItem];
}

// 是否一样两个列表
-(BOOL) isAlike:(NSArray *) musiclist {
    if(musiclist == nil || self.musiclist == nil) {
        return NO;
    }
    if(musiclist.count != self.musiclist.count) {
        return NO;
    }
    
    for (int i = 0; i < musiclist.count; i ++) {
        if(((YbrMusicItem *)[musiclist objectAtIndex:i]).musicId != ((YbrMusicItem *)[self.musiclist objectAtIndex:i]).musicId) {   // 只要有一个音乐的ID不相同就返回其他的地方
            return NO;
        }
        // 这里表示如果大于50个的歌曲是相同的话就认为两个列表是相同的了
        if(i > 50) {
            return NO;
        }
    }
    return YES;
}

// 返回Arr : YbrMusicItem 正在播放的Item
-(YbrMusicItem *) getQueueItem {
    return self.musicItem;
}

-(NSString *) getArtistName {
    if(self.musicItem != nil) {
        return self.musicItem.albumname;
    }
    return @"未知专辑";
}

-(NSString *) getSingerName {
    if(self.musicItem != nil) {
        return self.musicItem.singername;
    }
    return @"未知歌手";
}
-(NSString *) getMusicName {
    if(self.musicItem != nil) {
        return self.musicItem.musicName;
    }
    return @"未知歌曲";
}

-(int) getDuration {
    if(self.playType == 0) {
        if(self.avaPlayer != nil) {
            return self.avaPlayer.duration;
        }
    }else if (self.playType == 1) {
        if(self.httpPlayer != nil) {
            return self.httpPlayer.duration;
        }
    }
    return 0;
}

-(int) getPoisiton {
    if(self.playType == 0) {
         if(self.avaPlayer != nil) {
             return self.avaPlayer.currentTime;
         }
    }else if (self.playType == 1) {
        if(self.httpPlayer != nil) {
            return self.httpPlayer.progress;
        }
    }
    return 0;
}

// 设置播放哪一个
-(void) setQueuePosition:(int) index {
    if(index >= 0 && index < self.playLen) {
        self.playPos = index;
        self.isWillPlay = YES;
        [self playCurrent];
    }
}

-(NSString *) getBitmap {
    return self.musicItem.img;
}

-(BOOL) isPlaying {
    if(self.playType == 0) {
        return self.avaPlayer.isPlaying;
    }else {
        return self.httpPlayer.isPlaying;
    }
    return NO;
}
+(BOOL)playState
{
    if(ybrPlayer.playType != 0) {
        if (!ybrPlayer.isWillPlay) {
            return YES;
        }
        if (ybrPlayer.httpPlayer.isIdle) {
            return NO;
        }else if (ybrPlayer.httpPlayer.isWaiting)
        {
            return NO;
        }else if (ybrPlayer.httpPlayer.isPaused)
        {
            return YES;
        }else if (ybrPlayer.httpPlayer.isPlaying){
            return YES;
        }
    }
    return NO;
}

-(int) getQueuePosition {
    return self.playPos;
}
// 正在播放的音频的ID
-(int) getAudioId {
    if(self.musicItem != nil) {
        return self.musicItem.musicId;
    }
    return -1;
}

// 获取播放下一曲的index
-(int) getNextPos {
    if(self.playPos >= self.playLen - 1) {
        return 0;
    }
    return self.playPos + 1;
}

-(void) Next {
    self.playPos = [self getNextPos];
    self.isWillPlay = YES;
    [self playCurrent];
}


// 获取播放上一曲的index
-(int) getPrevPos {
    if(self.playPos == 0) {
        return self.playLen - 1;
    }
    
    return self.playPos - 1;
}


-(void) Prev {
    self.playPos = [self getPrevPos];
    self.isWillPlay = YES;
    [self playCurrent];
}


-(void) PlayOrPause {
    if(self.playType == 0) {
        if(self.avaPlayer.isPlaying) {
            [self.avaPlayer pause];
        }else {
            [self.avaPlayer play];
        }
    }else if(self.playType == 1){
        if(self.httpPlayer.isPlaying) {
            [self.httpPlayer pause];
        }else {
            [self.httpPlayer start];
        }
    }
    
    [self setPlayStateChange];
}

-(void) Play {
    if(self.playType == 0) {
        if(!self.avaPlayer.isPlaying) {
            [self.avaPlayer play];
        }
    }else if(self.playType == 1){
        if(!self.httpPlayer.isPlaying) {
            [self.httpPlayer start];
        }
    }
    
    [self setPlayStateChange];
}


-(void) stop {
    [self stopNoSendChange];
    [self setPlayStateChange];
}


-(void) stopNoSendChange {
    if(self.playType == 0) {
        [self.avaPlayer stop];
    }else if (self.playType == 1) {
        [self.httpPlayer stop];
        self.httpPlayer = nil;
    }
}


// 滑动到某一个位置
-(void) seek:(NSTimeInterval) pos {
    if(self.playType == 0) {
        self.avaPlayer.currentTime = pos;
    }else if(self.playType == 1) {
        [self.httpPlayer seekToTime:pos];
    }
}

-(BOOL) isHaveMusic {
    if(self.musiclist == nil || self.musiclist.count == 0) {
        return NO;
    }
    return YES;
}


// 这一首已经播放完了播放下一曲
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"播放完了  === %i" ,flag);
    [self Next];
}

// 解码错误
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    NSLog(@"编码错误  %@" ,error);
    [self Next];
}

// 处理中断(别人的)
- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player
{
    NSLog(@"处理中断");
}

// 处理中断结束
- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player
{
    NSLog(@"处理中断结束");
}


@end
